package com.js.nickcar.module.addcar.model;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;

import com.js.nickcar.base.BaseRecyclerViewFragment;
import com.js.nickcar.entity.remote.CarModelBean;
import com.js.nickcar.entity.remote.CarModelYearBean;
import com.js.nickcar.entity.remote.CarSeriesBean;
import com.js.nickcar.widget.recycler.BaseRecyclerAdapter;

import java.util.ArrayList;

/**
 * Created by LZY on 2017/10/4.
 */

public class CarModelFragment extends BaseRecyclerViewFragment<CarModelYearBean, CarModePresenter>
        implements CarModelView, CarModelAdapter.onCarModelSelectListener {

    public static final String EXTRA_CAR_SERIES = "car_series_id";
    public static final String EXTRA_SELECTED_CAR_MODEL = "selected_car_model";
    public CarSeriesBean mCarSeries;

    @Override
    protected BaseRecyclerAdapter<CarModelYearBean> getRecyclerAdapter() {
        CarModelYearAdapter adapter = new CarModelYearAdapter(getContext());
        adapter.setOnCarModelSelectListener(this);
        return adapter;
    }

    @Override
    protected CarModePresenter createPresenter() {
        return new CarModePresenter();
    }

    @Override
    protected void initBundle(Bundle bundle) {
        super.initBundle(bundle);
        mCarSeries = bundle.getParcelable(EXTRA_CAR_SERIES);
        if (mCarSeries != null) {
            mPresenter.setCarSeriesId(mCarSeries.getCar_series_id());
        }
    }

    public static CarModelFragment getInstance(CarSeriesBean carSeriesBean) {
        CarModelFragment modelFragment = new CarModelFragment();
        Bundle args = new Bundle();
        args.putParcelable(EXTRA_CAR_SERIES, carSeriesBean);
        modelFragment.setArguments(args);
        return modelFragment;
    }

    @Override
    public void onItemClick(int position, long itemId) {
        super.onItemClick(position, itemId);
        CarModelYearBean item = mAdapter.getItem(position);
        item.setSelected(!item.isSelected());
        ArrayList<CarModelBean> models = item.getModels();
        if (models == null || models.size() == 0) {
            mPresenter.requestCarModelData(item.getCar_model_year_id(), item, position);
        }else {
            mAdapter.notifyItemChanged(position);
        }
    }

    @Override
    protected String getTitle() {
        return mCarSeries == null ? super.getTitle() : mCarSeries.getSeries_name();
    }

    @Override
    public void notifyItemChanged(int position) {
        mAdapter.notifyItemChanged(position);
    }

    @Override
    public void onCarModelSelect(CarModelBean item, int position) {
        Fragment targetFragment = getTargetFragment();
        Intent data = new Intent();
        data.putExtra(EXTRA_SELECTED_CAR_MODEL,item);
        targetFragment.onActivityResult(getTargetRequestCode(),Activity.RESULT_OK,data);
        finish();
    }
}
